package com.dapangdong.testdemo.utils;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.view.PoiBaseView;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * <p>
 *
 * </p>
 *
 * @author : yhd
 * @since : 2023-04-27 14:20
 */
@Slf4j
public class ExcelUtil {

    /**
     * excel 导出(根据注解导出)
     *
     * @param dataList 数据列表
     * @param fileName 导出时的excel名称
     * @param response 输出流
     */
    public static void exportExcel(List<?> dataList, String fileName, String sheetName, Class<?> pojoClass, HttpServletResponse response, HttpServletRequest request) {
        // 配置导出参数
        ExportParams exportParams = new ExportParams(null, sheetName);
        // 创建数据模型Map
        Map<String, Object> map = new HashMap<>(5);
        map.put(NormalExcelConstants.DATA_LIST, dataList);
        map.put(NormalExcelConstants.CLASS, pojoClass);
        map.put(NormalExcelConstants.PARAMS, exportParams);
        map.put(NormalExcelConstants.FILE_NAME, fileName);
        // 导出Excel并发送给浏览器
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    /**
     * 根据模板导出excel
     *
     * @param map          数据模型Map
     * @param templateUrl  模板路径
     * @param fileName     导出时的excel名称
     * @param scanAllSheet 是否输出全部的sheet
     * @param sheetName    sheet的名称,可不填
     * @param response     输出流
     */
    public static void exportExcelByTemplate(Map<String, Object> map, String templateUrl, String fileName, boolean scanAllSheet, HttpServletResponse response, String... sheetName) throws IOException {
        //加载模板
        TemplateExportParams templateExportParams = new TemplateExportParams(templateUrl, scanAllSheet, sheetName);

        //创建一个Workbook对象，对应一个Excel文件，把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, map);

        downLoadExcel(fileName, workbook, response);
    }

    /**
     *
     * @param file
     * @param classType
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> classType) throws Exception {
        ImportParams params = new ImportParams();
        return ExcelImportUtil.importExcel(file.getInputStream(), classType, params);
    }


    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param response     输出流
     * @param exportParams 导出参数（标题、sheet名称、是否创建表头，表格类型）
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
                                      ExportParams exportParams) throws IOException {
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, workbook, response);
    }

    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param exportParams 导出参数（标题、sheet名称、是否创建表头，表格类型）
     * @param response     输出流
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams,
                                   HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list      数据列表
     * @param title     表格内数据标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  导出时的excel名称
     * @param response  输出流
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }


    /**
     * excel 导出
     *
     * @param list           数据列表
     * @param title          表格内数据标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       导出时的excel名称
     * @param isCreateHeader 是否创建表头
     * @param response       输出流
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }


    /**
     * excel下载
     *
     * @param fileName 下载时的文件名称
     * @param workbook excel数据
     * @param response 输出流
     */
    private static void downLoadExcel(String fileName, Workbook workbook, HttpServletResponse response) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName , StandardCharsets.UTF_8)+ ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            // 刷新缓冲区
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("导出失败: {}", e.getMessage());
            throw new IOException(e.getMessage());
        }
    }


    /**
     * excel 导入，有错误信息
     *
     * @param file      上传的文件
     * @param pojoClass pojo类型
     */
    public static <T> ExcelImportResult<T> importExcelMore(MultipartFile file, Class<T> pojoClass) throws IOException {
        if (file == null) {
            return null;
        }
        try {
            return importExcelMore(file.getInputStream(), pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param pojoClass   pojo类型
     */
    public static <T> List<T> importExcel(InputStream inputStream, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        //表格内数据标题行
        params.setTitleRows(1);
        //表头行
        params.setHeadRows(1);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param pojoClass   pojo类型
     */
    private static <T> ExcelImportResult<T> importExcelMore(InputStream inputStream, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        //表格内数据标题行
        params.setTitleRows(1);
        //表头行
        params.setHeadRows(1);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        try {
            return ExcelImportUtil.importExcelMore(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }
}
